#include "gps.h"
#include "uart.h"
#include "lcd.h"

volatile unsigned char have_fix;

gps_log xdata gl;
volatile unsigned short gps_page_ptr;
volatile unsigned short gps_byte_ptr;

void process_gpgga(){
	//          1         2         3         4         5         6          1
	//0123456789012345678901234567890123456789012345678901234567890123456789
	//$GPGGA,170834,4124.8963,N,08151.6838,W,1,05,1.5,280.2,M,-34.0,M,,,*75 
	get_field(uartBuffer, temp_pos_str, sizeof temp_pos_str, 9);
	curr_alt = (unsigned int)(atof(temp_pos_str) * 3.28f);
	//gl.alt = (unsigned short)curr_alt;
}

void process_gprmc(){

	//          1         2         3         4         5         6     	7
	//01234567890123456789012345678901234567890123456789012345678901234567890123
	//$GPRMC,225446.000,A,4916.4500,N,12311.1200,W,000.5,054.7,191194,020.3,E*68
	//    0    1        2     3     4     5   6    7      8      9	   10
	//-12.45675, -012.12341
	gl.header = GPS_LOG_HEADER;
	memset(pos_line, 0x20, sizeof pos_line);
					
	//latitude
	get_field(uartBuffer, temp_pos_str, sizeof temp_pos_str, 3);
	temp_pos = (temp_pos_str[0] - 0x30) * 10 + (temp_pos_str[1] - 0x30) + (atof(temp_pos_str + 2) / 60.0f);
	gl.lat = temp_pos;
	sprintf(pos_line + 1, "%f", temp_pos);
	if(uartBuffer[30] == 'S'){
		pos_line[0] = '-';
		gl.lat *= -1;
	}

	//longitude
	get_field(uartBuffer, temp_pos_str, sizeof temp_pos_str, 5);
	temp_pos = (temp_pos_str[0] - 0x30) * 100 + (temp_pos_str[1] - 0x30) * 10 + (temp_pos_str[2] - 0x30) + (atof(temp_pos_str + 3) / 60.0f);
	gl.lon = temp_pos;
	pos_line[9] = ',';
	
	if(uartBuffer[43] == 'W'){
		pos_line[10] = '-';
		gl.lon *= -1;
	}
	sprintf(pos_line + 11, "%f", temp_pos);
	lcd_write_string_at_pos(pos_line, 1, 0, 20);

	memset(pos_line, 0x20, sizeof pos_line);

	//speed
	get_field(uartBuffer, temp_pos_str, sizeof temp_pos_str, 7);
	prev_speed = curr_speed;
	curr_speed = (atof(temp_pos_str) * 1.15078f);
	if(curr_speed < 3)
		curr_speed = 0;

	gl.speed = curr_speed;
	
	temp_int = (int)curr_speed;
	//if(curr_speed > 100)
	//	sprintf(pos_line, "%dmph", temp_int);
	if(curr_speed > 10)
		sprintf(pos_line + 1, "%dmph", temp_int);
	else
		sprintf(pos_line + 2, "%dmph", temp_int);

	//heading
	get_field(uartBuffer, temp_pos_str, sizeof temp_pos_str, 8);	
	temp_int = atoi(temp_pos_str);
	gl.heading = temp_int;

	//time
	get_field(uartBuffer, gl.time, 6, 1);
	//date
	get_field(uartBuffer, gl.date, 6, 9);

	if(curr_speed)
		sprintf(pos_line + 6, " %d\1 %dft        ", temp_int, curr_alt);
	else
		sprintf(pos_line + 6, " ---\1 %dft        ", curr_alt);

	lcd_write_string_at_pos(pos_line, 2, 0, 20);

	memset(pos_line, 0x20, sizeof pos_line);
	sprintf(pos_line, "%f", odometer);
	sprintf(pos_line + 6, " %f", trip);
	//01234567890123456789
	//104*F 204567 1999.90
	lcd_write_string_at_pos(pos_line, 3, 6, 14); 
	
}
